package net.valerijtimakov.homefinances.dao.storages.common.mysql.query_builders;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import net.valerijtimakov.homefinances.exceptions.AppExceptionWrongState;

public class InsertQuery extends Query {
	
	private Map<String, Object> insertedFields = new HashMap<String, Object>();
	
	public InsertQuery() {
		super();
	}

	public InsertQuery(String tableName) {
		super(tableName);
	}
	
	public void setFieldValue(String fieldName, Object fieldValue) {
		insertedFields.put(fieldName, fieldValue);
	}
	
	@Override
	public String getSql() throws AppExceptionWrongState {
		StringBuilder res = getSqlSb();
		res.append(";");
		return res.toString();
	}
	
	protected StringBuilder getSqlSb() throws AppExceptionWrongState {
		if (tableName == null || tableName.isEmpty()) {
			throw new AppExceptionWrongState("Не задано имя таблицы!");
		}
		StringBuilder inserValuesLine = getFieldValuesLine();
		StringBuilder insertNamesLine = getFieldNamesLine();
		StringBuilder res = new StringBuilder();
		if (insertNamesLine.length() == 0 || inserValuesLine.length() == 0) {
			return res;
		}
		res.append("INSERT INTO `");
		res.append(tableName);
		res.append("` ");
		res.append(insertNamesLine);
		res.append(" VALUES ");
		res.append(inserValuesLine);
		return res;
	}
	
	protected StringBuilder getFieldValuesLine() {
		StringBuilder res = new StringBuilder();
		for (String fName : getFieldNamesSet()) {
			if (res.length() > 0) {
				res.append(",");
			}
			res.append(MySqlUtils.getValueLine(insertedFields.get(fName)));
		}
		res.insert(0, "(");
		res.append(")");
		return res;
	}
	
	protected StringBuilder getFieldNamesLine() throws AppExceptionWrongState {
		StringBuilder res = new StringBuilder();
		MySqlUtils.appendDBItemNames(res, getFieldNamesSet());
		res.insert(0, "(");
		res.append(")");
		return res;
	}
	
	protected Set<String> getFieldNamesSet() {
		return insertedFields.keySet();
	}

}
